<?php 

class Form {

	var $_html;	
	var $errors;
	var $fields;
	
	public function __construct($fields = array(), $attributes = array()){
		$this->_html = new Html("form", $attributes);
		$this->errors = array();
		$this->fields = $fields;
	}
	
	public function populate($data = array()){
		foreach($data as $name => $value){
			if(array_key_exists($name, $this->fields)){
				$this->fields[$name]->setValue($value);
			}
		}
	}
	
	public function getData(){
		$data = array();
		foreach($this->fields as $name => $field){
			$data[$name] = $field->getValue();
		}
		return $data;
	}
	
	public function isValid(){
		foreach($this->fields as $name => $field){
			if($field->isRequired()){
				if(!$field->isValid()){
					$this->errors[] = $name;
				}
			}
		}
		return empty($this->errors);
	}
	
	public function clean(){
		foreach($this->fields as $name => $field){
			$field->clean();
		}
		$this->errors = array();
	}
	
	public function containsError($name){
		return $this->fields[$name]->containsError();	
	}
	
	public function getValue($name){
		return $this->fields[$name]->getValue();	
	}
	
	public function open($attrs = array("method" => "post")){
		return $this->_html->open($attrs);
	}
	
	public function close(){
		return $this->_html->close();
	}
	
	public function render($field, $attrs = array()){
		return $this->fields[$field]->render($field, $attrs);
	}
	
	public function label($field_name){
		$attrs = array("for" => $field_name);
		$field = $this->fields[$field_name];
		if($field->containsError()){
			if(!array_key_exists("class", $attrs)){
				$attrs["class"] = "field-with-error";
			} else {
				$attrs["class"] .= " field-with-error";
			}
		}
		$label = new Html("label", $attrs);
		$label->setInner(ucfirst($field_name));
		return $label->render();
	}
	
	public function submit($text = "Submit"){
		$button = new Html("button", array("type" => "submit"));
		$button->setInner($text);
		return $button->render();
	}
	
}